﻿<html>
<head>
	<link rel="shortcut icon" href="favicon.ico">
	<title>Hải quan Việt Nam - Open Street Map - Leaflet</title>
	<script>
		var sUrl_OSM_Server = 'http://10.15.144.78:8080/api/';
	</script>	
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="css/bootstrap.min.css" >

	
	<script src="js/jquery-1.12.0.min.js"></script>
	<!-- Latest compiled and minified JavaScript -->
	<script src="js/bootstrap.min.js" ></script>

	<link rel="stylesheet" href="css/leaflet.css" />
	<link rel="stylesheet" href="css/leaflet.draw.css" />
	<style>
		#map {position: absolute; width: 100%; height: 100%;}	
		#divInfo {display: none;}
	</style>
	
	<script src="js/leaflet.js"></script>
	<script src="js/leaflet.draw.js"></script>
	<!-- 
	<script src="js/Control.OSMGeocoder.js"></script>
	<script src="http://10.15.144.78:8080/api/Resource.ashx?sRID=js"></script>
	<script src="js/countries.js" type="text/javascript"></script>
	<script type="text/javascript" src="js/leaflet.ajax.js"></script>
	<script src="js/esri-leaflet.js"></script>
	-->
	<script src='js/Leaflet.fullscreen.min.js'></script>
	<link href='css/leaflet.fullscreen.css' rel='stylesheet' />
	
	
	<script src='js/Control.Geocoder.js'></script>
	<link href='css/Control.Geocoder.css' rel='stylesheet' />
	
	<script src='js/leaflet-routing-machine.js'></script>
	<link href='css/leaflet-routing-machine.css' rel='stylesheet' />
	 
	 
  
</head>
<body>
	<div id="map"></div>
	<div id="basemaps-wrapper" class="leaflet-bar">
  <select name="basemaps" id="basemaps" onChange="changeBasemap(basemaps)">
    <option value="Topographic">Topographic<options>
    <option value="Streets">Streets</option>
    <option value="NationalGeographic">National Geographic<options>
    <option value="Oceans">Oceans<options>
    <option value="Gray">Gray<options>
    <option value="DarkGray">Dark Gray<options>
    <option value="Imagery">Imagery<options>
    <option value="ShadedRelief">Shaded Relief<options>
  </select>
</div>
	<div id="divInfo" class="container bs-docs-container"><br><br>
		<div style="width:50%; float:left;">
			<div class="dropdown">
				<button class="btn btn-default dropdown-toggle" type="button" id="ddlmECustoms" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">-- Lựa chọn cảng --<span class="caret"></span></button>
				<ul id="tblECustoms" class="dropdown-menu" aria-labelledby="ddlmECustoms"></ul>
			</div>
		</div>
		<div style="width:50%; float:right;">
			<div class="input-group">
				<div class="dropdown">
					<button class="btn btn-default dropdown-toggle" type="button" id="ddlmFeatureGroup" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" style="width: 100%;">-- Lựa chọn map --<span class="caret"></span></button>
					<ul id="tblFeatureGroup" class="dropdown-menu" aria-labelledby="ddlmFeatureGroup" style="width: 100%;"></ul>
				</div>
				<span class="input-group-btn"><button onclick="getGeoJSON_FeatureGroup();return false;" class="btn btn-info">Load FeatureGroup</button></span>
			</div>
		</div><br><br><br>
		<hr/>
		<label id="lblMsg" style="color:Red;"></label><br>
		<div class="input-group">
			<input id="txtsFeatureGroup" type="text" class="form-control" autocomplete="off" placeholder="Mời nhập tên map" autofocus>
			<span class="input-group-btn"><button onclick="setGeoJSON_FeatureGroup();return false;" class="btn btn-info">Save FeatureGroup</button></span>
		</div><br><br><br>
	</div>
	
	<script>
		$( document ).ready(function() {
			getList_ECustoms();
			getGeoJSON_FeatureGroup();
			setInterval(function(){ getList_ECustoms(); }, 30000);
		});
			
		
		var markers = new L.FeatureGroup();
		
		
		//Markers With Custom Icons
		var seaport = L.icon({iconUrl: 'js/images/anchor.png'});

		//BEGIN init map ==================================================================================
		var map = L.map('map').setView([21.017030, 105.783902], 13);
		L.tileLayer(sUrl_OSM_Server + 'Resource.ashx?sRID={s}_{z}_{x}_{y}', {
			attribution: '&copy; <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors'
		}).addTo(map);
		
		var southWest = L.latLng(7.9722, 102.65625),//tây nam
			northEast = L.latLng(23.42293, 108.7207),//đông bắc
			bounds = L.latLngBounds(southWest, northEast);
		map.setMaxBounds(bounds);

		//countries
		//var countryStyle = {'color': "#000", 'weight': 2, 'opacity': 0.6};
		//L.geoJson(countries, {onEachFeature: popup, style: countryStyle }).addTo(map);

		//Search	//bing('ApA2fpMOTDBGCpkxhrrrC5tI5rlGhNp64_ZIqTgRg_N6qbZC3jZh16uGZxSnRfMa')
		var osmGeocoder = new L.Control.Geocoder({collapsed:true, position:'topleft', placeholder:'Tìm kiếm...', errorMessage:'Không tìm thấy.', showResultIcons:true, geocoder:new L.Control.Geocoder.nominatim()});
		map.addControl(osmGeocoder);
		
		
		
		L.Routing.control({language:'vi', collapsible:true, show:false, position:'topleft', routeWhileDragging: true, geocoder: L.Control.Geocoder.nominatim()}).addTo(map);
		//END init map ==================================================================================
		
		
		
		
		//BEGIN add single marker to our map ==================================================================================
		//var marker = L.marker([21.017030, 105.783902],{icon: seaport,option1: true,                 // a boolean value
		//    option2: 'a string lives here', // a string
		//    PK_iCID: 1234}                  // a number
		//	).addTo(map).bindPopup('<center>FPS - FIS<br> FPT</center>').openPopup();
		//marker.options.alt="ID";
		//markers.addLayer(marker);
		//END add single marker to our map ==================================================================================
		
		
		
		//BEGIN add multiple markers to our map =============	
		//	for (var i = 0; i < planes.length; i++) {
		//		marker = new L.marker([planes[i]['dLatitude'],planes[i]['dLongitude']],{PK_iCID:planes[i]['PK_iCID']})
		//			.bindPopup(planes[i]['sName'] + ' - ' + planes[i]['iContainer'])
		//			.addTo(map);
		//			markers.addLayer(marker);
		//	}
		//END add multiple markers to our map ==================================================================================
		
		map.addLayer(markers);
		
		
		
		//BEGIN event map click ==================================================================================
		var popup = L.popup();
		function onMapClick(e) {
			popup
				.setLatLng(e.latlng)
				.setContent("You clicked the map at " + e.latlng.toString())
				.openOn(map);
			//L.marker(e.latlng).addTo(map).bindPopup('<center>FPS - FIS<br> FPT</center>').openPopup();
		}
		//map.on('click', onMapClick);
		//END event map click ==================================================================================

		
		//BEGIN event mark click ==================================================================================
		//marker.on('click', function(e) {
		//	alert(e.target.options.PK_iCID);
		//});
		//END event mark click ==================================================================================



		
		
		//BEGIN tool edit draw ==============================================================================
		// Initialise the FeatureGroup to store editable layers
		var drawnItems = new L.FeatureGroup();
		map.addLayer(drawnItems);

		// Initialise the draw control and pass it the FeatureGroup of editable layers
		var drawControl = new L.Control.Draw({
			draw: {
				position: 'topleft',
				polygon: {
					title: 'Draw a sexy polygon!',
					allowIntersection: false,
					drawError: {
						color: '#b00b00',
						timeout: 1000
					},
					shapeOptions: {
						color: '#bada55'
					},
					showArea: true
				},
				polyline: {
					metric: false
				},
				circle: {
					shapeOptions: {
						color: '#662d91'
					}
				}
			},
			edit: {
				featureGroup: drawnItems
			}
		});
		map.addControl(drawControl);

		map.on('draw:created', function (e) {
			//var type = e.layerType,
				layer = e.layer;

			//if (type === 'marker') {
			//	layer.bindPopup('A popup!');
			//}
			
			
	
			
			drawnItems.addLayer(layer);
			//var a = drawnItems._layers;
			//alert(a);//.properties["radius"] = layer.getRadius();
			//}
		});
		
		map.on('draw:edited', function (e) {
		var layers = e.layers;
		var jsona =JSON.stringify(drawnItems.toGeoJSON());
		//alert(jsona);
		layers.eachLayer(function (layer) {
			//do whatever you want, most likely save back to db
			
			});
		});
		//END tool edit draw ==============================================================================
		
		
		

		//BEGIN fullscreen ==============================================================================
		L.control.fullscreen().addTo(map);
		//END fullscreen ==============================================================================

		//var geojsonLayer = new L.GeoJSON.AJAX("js/data_draw.js");
		//L.geoJson(geojsonLayer).addTo(map);



  
		
		
	/*		
		// hydrology overlay layer
		var hydro = L.esri.tiledMapLayer('http://hydrology.esri.com/arcgis/rest/services/WorldHydroReferenceOverlay/MapServer');
		// basemap layer groups so the hydro overlay always overlays the various basemaps
		var nationalGeographic = L.layerGroup([hydro, L.esri.basemapLayer('NationalGeographic')
		]),
		esriTopo = L.layerGroup([hydro, L.esri.basemapLayer('Topographic')
		]),
		esriShadedRelief = L.layerGroup([L.esri.tiledMapLayer('ShadedReliefLabels'), hydro, L.esri.basemapLayer('ShadedRelief')
		]),
		esriImagery = L.layerGroup([hydro, L.esri.basemapLayer('Imagery')
		]);
		// add default layers to map
		map.addLayer(esriTopo);
		// json object for layer switcher control basemaps
		var baseLayers = {"National Geographic": nationalGeographic, "Esri Topographic": esriTopo, "Shaded Relief": esriShadedRelief, "Imagery": esriImagery
		};
		var overlayMaps = {"Hydro": hydro};
		// add layer groups to layer switcher control
		var controlLayers = L.control.layers(baseLayers, overlayMaps).addTo(map);
	*/
		
		
		

		function getList_ECustoms(){
			map.removeLayer(markers);
			$.ajax({
                type: "POST",
                url: sUrl_OSM_Server + "OSM.asmx/getList_ECustoms",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var planes2 = JSON.parse(data.d);
					$("#tblECustoms").children().remove();
					var str = '';
					//BEGIN add multiple markers to our map =============	
						for (var i = 0; i < planes2.length; i++) {
							str += '<li><a href="#" data-zoom="12" data-position="' + planes2[i]['dLatitude'] + ','+ planes2[i]['dLongitude'] +'"    onclick="goto_mark(this);return false;">'+planes2[i]['sName'] +'</a></li>';
							
							
							marker = new L.marker([planes2[i]['dLatitude'],planes2[i]['dLongitude']],{icon: seaport, PK_iCID:planes2[i]['PK_iCID']})
								.bindPopup(planes2[i]['sName'] + ' - ' + planes2[i]['iContainer'])
								.addTo(map);
								markers.addLayer(marker);
								
								marker.on('mouseover', function(e) {
									//marker.openPopup();
									//alert(e.target.options.PK_iCID);
								});
						}
						str += '';
						$(str).appendTo("#tblECustoms");
					//END add multiple markers to our map ==================================================================================
	
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " + errorThrown);
                }
            });
		}

		function goto_mark(_this){
			var pos = $(_this).attr('data-position');
			var zoom = $(_this).attr('data-zoom');
			if (pos && zoom) {
				var locat = pos.split(',');
				var zoo = parseInt(zoom);
				map.setView(locat, zoo, {animation: true});
				return false;
			}
		}

		
		function getGeoJSON_FeatureGroup(){
			$.ajax({
                type: "POST",
                url: sUrl_OSM_Server + "OSM.asmx/getList_FeatureGroup",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var result = JSON.parse(data.d);
					$("#tblFeatureGroup").children().remove();
					var str = '';
					for (var i = 0; i < result.length; i++) {
						str += '<li><a href="#" onclick="getGeoJSON_FeatureGroup_ByPK_iFGID('+ result[i]['PK_iFGID'] +');return false;">'+result[i]['sFeatureGroup'] +'</a></li>';
					}
					str += '';
					$(str).appendTo("#tblFeatureGroup");	
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " + errorThrown);
                }
            });
		}
		
		
		var layer_draw = new L.FeatureGroup();
		function getGeoJSON_FeatureGroup_ByPK_iFGID(_PK_iFGID){
			map.removeLayer(layer_draw);
			layer_draw = new L.FeatureGroup();
			$.ajax({
                type: "POST",
                url: sUrl_OSM_Server + "OSM.asmx/getGeoJSON_FeatureGroup_ByPK_iFGID",
                data: "{'PK_iFGID':'" + _PK_iFGID + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var result = JSON.parse(data.d);
					layer_draw.addLayer(L.geoJson().addData(result));
					map.addLayer(layer_draw);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " + errorThrown);
                }
            });
		}
		
		
		function setGeoJSON_FeatureGroup(){
			$('#lblMsg').html("");
			if(txtsFeatureGroup.value.trim() =="")
			{
				$('#lblMsg').html("Bạn chưa nhập tên bản đồ.");
				txtsFeatureGroup.focus();
				return;
			}
			if(drawnItems.toGeoJSON().features.length <=0)
			{
				$('#lblMsg').html("Bạn chưa vẽ bản đồ nào.");
				return;
			}
			$.ajax({
                type: "POST",
                url: sUrl_OSM_Server + "OSM.asmx/setGeoJSON_FeatureGroup",
                data: "{'sFeatureGroup':'" + txtsFeatureGroup.value + "','sGeoJSON':'"+JSON.stringify(drawnItems.toGeoJSON()) +"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d == true)
					{
						$('#lblMsg').html("Thêm thành công");
						txtsFeatureGroup.value = "";
					}
					else
						$('#lblMsg').html("Thêm thất bại, Vui lòng kiểm tra lại!");
					getGeoJSON_FeatureGroup();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " + errorThrown);
                }
            });
		}
	</script>
</body>
<html>